let http = require("http");
let crypto = require("crypto");
const path = require("path");

const { spawn } = require("child_process");
const sendMail = require("./sendMail");
let SECRET = "123456";
function sign(body) {
  return `sha1=` + crypto.createHmac("sha1", SECRET).update(body).digest("hex");
}

let webHookPwd = "123456";
let server = http.createServer(function (req, res) {
  if (req.method === "POST" && req.url === "/webhook") {
    let buffers = [];
    req.on("data", function (buffer) {
      buffers.push(buffer);
    });
    req.on("end", function (buffer) {
      let body = Buffer.concat(buffers).toString();
      let event = req.headers["x-gitee-event"];
      let pwd = req.headers["x-gitee-token"];

      console.log("接受到gitee的请求");
      console.log("event:" + event);
      console.log("pwd:" + pwd);
      console.log("body:" + body);

      if (pwd !== webHookPwd) {
        return res.end("not allowed");
      }
      res.setHeader("Content-Type", "application/json");
      res.end(JSON.stringify({ ok: true }));

      //   开始部署
      if (event == "Push Hook") {
        console.log("开始部署");
        let payload = JSON.parse(body);

        //windown下执行bat文件
        const dirPath = path.resolve(__dirname);
        const filePath = path.resolve(
          dirPath,
          `./${payload.repository.name}.bat`
        );

        exec(filePath, (error, stdout, stderr) => {
          if (error) {
            console.error(`执行的错误: ${error}`);
            return;
          }
          console.log(`stdout: ${stdout}`);
        });

        // let child = spawn("cmd", [filePath]);
        // let buffers = [];
        // child.stdout.on("data", function (buffer) {
        //   buffers.push(buffer);
        // });
        // child.stdout.on("end", function (buffer) {
        //   let logs = Buffer.concat(buffers).toString();
        //   console.log(logs);
        // sendMail(`
        //       <h1>部署日期:${new Date()}</h1>
        //       <h2>部署人:${payload.pusher.name}</h2>
        //       <h2>部署邮箱:${payload.pusher.email}</h2>
        //       <h2>提交信息:${
        //         payload.head_commit && payload.head_commit["message"]
        //       }</h2>
        //       <h2>部署日志:${logs.replace("\r\n", "<br/>")}</h2>
        // `);
        // });
      }
    });
  } else {
    res.end("not found");
  }
});
server.listen(4000, () => {
  console.log("http://localhost:4000");
});
